<?php

namespace MoChat\App\NewHome\Action;

use Hyperf\DbConnection\Db;
use MoChat\App\WorkDepartment\Contract\WorkDepartmentContract;
use MoChat\Framework\Action\AbstractAction;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Sales\Constants\SalesTaskStatusCode;
use MoChat\App\Sales\Contract\SalesClientTaskContract;
use MoChat\App\Sales\Contract\SalesClientTaskEmployeeContract;
use MoChat\App\Sales\Contract\SalesTaskContract;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Constants\ErrorCode;

/**
 * 员工排行
 * @Controller
 */
class EmployeeRank extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var WorkDepartmentContract
     */
    protected $workDepartmentService;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     * })
     * @RequestMapping(path="/dashboard/newHome/employeeRank", methods="GET")
     */
    public function handle()
    {
        $user = user();
        // 判断用户绑定企业信息
        if (!isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $data = $this->request->all();
        $this->validated($data);
        $data = $this->typeEnum($data);

        $callOut = Db::table('work_employee as employee')
            ->leftJoin('call_record as call', 'call.work_employee_id', '=', 'employee.id')
            ->where('call.call_type', '=', 'out')
            ->when(!empty($data['start_time']) && !empty($data['end_time']), function ($query) use ($data) {
                $query->where('call.created_time', '>=', $data['start_time']);
                $query->where('call.created_time', '<', $data['end_time']);
            })
            ->select([
                Db::raw('COUNT(mc_call.id) as number'),
                'employee.name',
                'employee.id',
            ])->groupBy([
                'employee.id'
            ])
            ->orderByRaw('number desc')
            ->limit(7)->get()->toArray();

        $clock = Db::table('work_employee as employee')
            ->leftJoin('clock_record as clock', 'clock.work_employee_id', '=', 'employee.id')
            ->when(!empty($data['start_time']) && !empty($data['end_time']), function ($query) use ($data) {
                $query->where('clock.created_at', '>=', $data['start_time']);
                $query->where('clock.created_at', '<', $data['end_time']);
            })
            ->select([
                Db::raw('COUNT(mc_clock.id) as number'),
                'employee.name',
                'employee.id',
            ])->groupBy([
                'employee.id'
            ])
            ->orderByRaw('number desc')
            ->limit(7)->get()->toArray();

        $order = Db::connection('b2b')->table('user_order as order')
            ->join('order_status as status', function ($query) {
                $query->on('status.ID', '=', 'order.ID')
                    ->where('status.STATUS_', '>=', 0);
            })
            ->join('user as user', 'user.id', '=', 'order.USER_ID')
            ->when(!empty($data['start_time']) && !empty($data['end_time']), function ($query) use ($data) {
                $query->where('order.CREATE_TIME', '>=', $data['start_time']);
                $query->where('order.CREATE_TIME', '<', $data['end_time']);
            })
            ->select([
                Db::raw('SUM(my_order.TOTAL_AMOUNT) as number'),
                'user.unique_id',
            ])->orderByRaw('number desc')->groupBy([
                'user.unique_id'
            ])->get()->toArray();
        $uniqueIds = empty($order) ? [] : array_column($order, 'unique_id');
        $employee = Db::table('client as client')
            ->join('work_employee as employee', 'employee.id', '=', 'client.work_employee_id')
            ->whereIn('client.unique_id', $uniqueIds)
            ->select([
                'employee.name',
                'client.unique_id'
            ])->get()->toArray();
        $employee = empty($employee) ? [] : array_column($employee, null, 'unique_id');
        $money = [];
        if (!empty($order)) {
            foreach ($order as $item) {
                if (isset($employee[$item->unique_id]->name)) {
                    $money[] = [
                        'name' => $employee[$item->unique_id]->name,
                        'number' => $item->number,
                    ];
                }
                if (count($money) == 7) {
                    break;
                }
            }
        }
        $list['callOut'] = $callOut;
        $list['visit'] = $clock;
        $list['wechat'] = [];
        $list['money'] = $money;

        return $list;
    }

    private function typeEnum($data): array
    {
        $timeRange = [];
        //今日
        if ($data['type'] == 1) {
            $timeRange = [
                'start_time' => date('Y-m-d 00:00:00'),
                'end_time' => date('Y-m-d H:i:s'),
            ];
        }
        //昨日
        if ($data['type'] == 2) {
            $timeRange = [
                'start_time' => date('Y-m-d 00:00:00', strtotime('-1 day')),
                'end_time' => date('Y-m-d 00:00:00'),
            ];
        }
        //本月
        if ($data['type'] == 3) {
            $timeRange = [
                'start_time' => date('Y-m-01 00:00:00'),
                'end_time' => date('Y-m-d H:i:s'),
            ];
        }
        //上月
        if ($data['type'] == 4) {
            $start = date('Y-m-01 00:00:00', strtotime('-1 month'));
            $timeRange = [
                'start_time' => date('Y-m-01 00:00:00', strtotime('-1 month')),
                'end_time' => date('Y-m-d H:i:s', strtotime('+1 month', strtotime($start))),
            ];
        }
        //本周
        if ($data['type'] == 5) {
            $week = date('w');
            $day = $week ? $week - 1 : 6;
            $timeRange = [
                'start_time' => date('Y-m-d 00:00:00', strtotime('-' . $day . ' day')),
                'end_time' => date('Y-m-d H:i:s'),
            ];
        }
        //默认
        return array_merge($data, $timeRange);
    }


    /**
     * 验证规则.
     */
    protected function rules(): array
    {
        return [
            'type' => 'in:0,1,2,3,4,5',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    protected function messages(): array
    {
        return [
            'type.in' => 'type参数错误',
        ];
    }

}
